package xtreamclient

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.io.FileReader
import java.io.FileWriter

class PropertyHandler {

    val gson = GsonBuilder().setPrettyPrinting().create()
    var loadedProperties: Properties? = null
    fun loadProperties(filename:String): Properties {
        val properties = gson.fromJson(FileReader(filename), Properties::class.java)
        loadedProperties = properties
        return properties
    }


    fun getNamedServerProperties():List<NamedServerProperties>? {
        if(loadedProperties!=null) {
            var i = 0
            val list = mutableListOf<NamedServerProperties>()
            for (server in loadedProperties!!.servers) {
                list.add(NamedServerProperties(i.toString(), server))
                i++
            }
            return list
        } else {
            return null
        }
    }

    fun addServerProperties(properties: ServerProperties) {
        val newProperties = loadedProperties?.servers?.toMutableList()?.let {
            it.add(properties)
            Properties(it) }
        loadedProperties = newProperties
    }

    fun removeServerProperties(properties: ServerProperties) {
        val newProperties = loadedProperties?.servers?.toMutableList()?.let {
            it.remove(properties)
            Properties(it)
        }
        loadedProperties = newProperties
    }

    fun writeProperties(filename: String) {
        val writer = FileWriter(filename,false)

        writer.write(gson.toJson(loadedProperties))
        writer.close()
    }


}

data class ServerProperties(val hostname:String, val port:Int, val username:String, val password:String) {
    fun getLiveStreamBase():String {
        return "$hostname:$port/live/$username/$password/"
    }

    fun getTimeshiftStreamBase():String {
        return "$hostname:$port/timeshift/$username/$password/"
    }

    fun getMovieStreamBase():String {
        return "$hostname:$port/movie/$username/$password/"
    }

    fun getSeriesStreamBase():String {
        return "$hostname:$port/series/$username/$password/"
    }
}

data class Properties(val servers:List<ServerProperties>)

data class NamedServerProperties(val id:String,val properties: ServerProperties)